package com.whoyx.jiebing.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.whoyx.jiebing.dao.entity.MsgRecordEntity;
import com.whoyx.jiebing.dao.entity.UserEntity;
import com.whoyx.jiebing.dao.service.IMsgRecordService;
import com.whoyx.jiebing.dao.service.IUserService;
import com.whoyx.jiebing.domain.enums.DeleteEnum;
import com.whoyx.jiebing.domain.enums.MsgTypeEnum;
import com.whoyx.jiebing.domain.msg.MsgBody;
import com.whoyx.jiebing.domain.msg.bo.CloudCustomData;
import com.whoyx.jiebing.domain.msg.bo.TIMCustomData;
import com.whoyx.jiebing.domain.msg.req.TimAdminSendMsgData;
import com.whoyx.jiebing.domain.msg.resp.TimResultMsg;
import com.whoyx.jiebing.domain.resp.PatientBaseInfoRespDto;
import com.whoyx.jiebing.domain.resp.UploadUrlRespDto;
import com.whoyx.jiebing.utils.RemoteUtils;
import com.whoyx.jiebing.utils.TLSSigAPIv2;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class AsyncService {
    private static final String BASE_SINGLE_IMPORT_URL = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?";
    private static final String BASE_ADMIN_SEND_MSG_URL = "https://console.tim.qq.com/v4/openim/sendmsg?";
    @Value("${tim.secret}")
    private String timSecret;
    @Value("${tim.appId}")
    private Long timAppId;
    @Value("${tim.serviceUid}")
    private String serviceUid;
    @Value("${third.debug}")
    private boolean thirdDebug;

    private final IMsgRecordService iMsgRecordService;
    private final IUserService iUserService;
    @Value("${third.guidanceUrl}")
    private String guidanceUrl;

    @Async
    public void sendGreetingMsg(UserEntity userEntity) {
        if (StringUtils.isNotBlank(userEntity.getTargetUid()) && userEntity.getTargetUid().equals(serviceUid) && userEntity.getGreetingMsg() == 1) {
            String patUid = userEntity.getUid();
            MsgRecordEntity msgRecordEntity = iMsgRecordService.getOne(
                    Wrappers.<MsgRecordEntity>lambdaQuery()
                            .and(w -> w.eq(MsgRecordEntity::getFromUid, patUid)
                                    .or().eq(MsgRecordEntity::getToUid, patUid))
                            .eq(MsgRecordEntity::getDeleted, DeleteEnum.ENABLE.getValue())
                            .gt(MsgRecordEntity::getMsgTime, userEntity.getTargetUpdateTime())
                            .orderByDesc(MsgRecordEntity::getMsgTime)
                            .last("limit 1")
            );
            // 未发送过初始化消息  或者 结束服务后未发送过初始化消息
            if (userEntity.getTargetUid().equals(serviceUid) && msgRecordEntity == null) {
                Map<String, Object> map = new HashMap<>();
                map.put("Text", "您好，我是智能医生助理小甲~");
                adminSendMsg(TimAdminSendMsgData.builder()
                        .syncOtherMachine(2)
                        .fromAccount(serviceUid)
                        .toAccount(userEntity.getUid())
                        .msgLifeTime(604800)
                        .msgRandom((long) RandomUtil.randomInt(100000, 1000000))
                        .msgBody(Collections.singletonList(MsgBody.builder()
                                .msgType(MsgTypeEnum.TIMTextElem.getName())
                                .msgContent(map)
                                .build()))
                        .build());
            }
            adminSendMsg(TimAdminSendMsgData.builder()
                    .syncOtherMachine(2)
                    .fromAccount(serviceUid)
                    .toAccount(userEntity.getUid())
                    .msgLifeTime(604800)
                    .msgRandom((long) RandomUtil.randomInt(100000, 1000000))
                    .msgBody(Collections.singletonList(MsgBody.builder()
                            .msgType(MsgTypeEnum.TIMCustomElem.getName())
                            .msgContent(TIMCustomData.builder()
                                    .Data("猜你想问")
                                    .build())
                            .build()))
                    .cloudCustomData(JSONUtil.toJsonStr(CloudCustomData.builder()
                            .type(7)
                            .content("猜你想问")
                            .build()))
                    .build());
            userEntity.setGreetingMsg(2);
            iUserService.updateById(userEntity);

        }
    }


    public static String getEncodeUrl(String path, Long sdkAppId, String sdkSecret) {
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(sdkAppId, sdkSecret);
        String sig = null;
        try {
            sig = tlsSigAPIv2.genUserSig("administrator", 604800L);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        String baseUrl = path +
                String.format("sdkappid=%d&identifier=%s&usersig=%s&random=%d&contenttype=%s"
                        , sdkAppId, "administrator", sig, RandomUtil.randomInt(1, 429496729), "json");
        log.info("[发送TIM消息]，baseUrl：{}", baseUrl);
        return baseUrl;
    }

    public void adminSendMsg(TimAdminSendMsgData timAdminSendMsgData) {
        String baseUrl = getEncodeUrl(BASE_ADMIN_SEND_MSG_URL, timAppId, timSecret);
        Map<String, Object> paramsMap = new HashMap<>();
        if (timAdminSendMsgData.getForbidCallbackControl() != null) {
            paramsMap.put("ForbidCallbackControl", timAdminSendMsgData.getForbidCallbackControl());
        }
        paramsMap.put("From_Account", timAdminSendMsgData.getFromAccount());
        paramsMap.put("To_Account", timAdminSendMsgData.getToAccount());
        paramsMap.put("SyncOtherMachine", timAdminSendMsgData.getSyncOtherMachine());
        paramsMap.put("MsgRandom", timAdminSendMsgData.getMsgRandom());
        List<Map<String, Object>> msgBodyList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("MsgType", timAdminSendMsgData.getMsgBody().get(0).getMsgType());
        map.put("MsgContent", timAdminSendMsgData.getMsgBody().get(0).getMsgContent());
        msgBodyList.add(map);
        paramsMap.put("MsgBody", msgBodyList);
        paramsMap.put("CloudCustomData", timAdminSendMsgData.getCloudCustomData());
        String respStr = RemoteUtils.sendPost(baseUrl, paramsMap);
        TimResultMsg timResultMsg = JSONUtil.toBean(respStr, TimResultMsg.class);
    }


    public UploadUrlRespDto uploadUrl(String patUid) {
        UserEntity userEntity = iUserService.validatedEntityByUid(patUid);
        String openId = userEntity.getOpenId();
        String path = guidanceUrl + "/index/" + openId + "?state=1";
        String uploadPictureUrl = "https://b.yicloud.org/dyn2/wx/2/1643/p/3157/live?opi=" + openId + "&returl=" + path;
        String questionnaireUrl = "https://b.yicloud.org/dyn2/wx/2/1643/p/3157/live?opi=" + openId + "&returl=" + path;
        if (thirdDebug) {
            uploadPictureUrl = "https://b.yicloud.org/dyn2/wx/2/1643/p/3157/live?opi=o6fsjuJsSpmRE1tf-0dlG7EesEA8" + "&returl=" + path;
            questionnaireUrl = "https://b.yicloud.org/dyn2/wx/2/1643/p/3157/live?opi=o6fsjuJsSpmRE1tf-0dlG7EesEA8" + "&returl=" + path;
        }
        return UploadUrlRespDto.builder()
                .uploadPictureUrl(uploadPictureUrl)
                .questionnaireUrl(questionnaireUrl)
                .build();
    }

    public String getUserInfoUrl(String openId, String dOpenId) {
//        UserEntity userEntity = iUserService.validatedEntityByUid(drUid);
//        String dOpenId = userEntity.getOpenId();
        String path = guidanceUrl + "/consultList/" + "CUSTOMER_SERVICE";
        String userInfoUrl = "https://b.yicloud.org/dyn2/wx/2/1643/p/3157/live?opi=" + openId + "&popi=" + dOpenId + "&returl=" + path;
        if (thirdDebug) {
            userInfoUrl = "https://b.yicloud.org/dyn2/wx/2/3069/p/admin?opi=o6fsjuImNhgzAQTm9sBekiweqXVc&popi=o6fsjuJsSpmRE1tf-0dlG7EesEA8" + "&returl=" + path;
        }
        return userInfoUrl;
    }

    public String getFollowUpUrl(String openId, String uid) {
        String path = guidanceUrl + "/index/" + openId + "?state=1";
        String userInfoUrl = "http://b.yicloud.org/dyn2/wx/2/1643/p/live?opi=" + openId + "&which=registration" + "&returl=" + path;
//        if (thirdDebug) {
//            userInfoUrl = "http://b.yicloud.org/dyn2/wx/2/1643/p/live?opi=o6fsjuImNhgzAQTm9sBekiweqXVc" + "&which=registration" + "&returl=" + path;
//        }
        return userInfoUrl;
    }

    public String getRegisterUrl(String openId, String uid) {
        String path = guidanceUrl + "/index/" + openId + "?state=1";
        String userInfoUrl = "https://b.yicloud.org/dyn2/wx/2/1643/p/index?opi=" + openId + "&returl=" + path;
//        if (thirdDebug) {
//            userInfoUrl = "https://b.yicloud.org/dyn2/wx/2/1643/p/index?opi=o6fsjuImNhgzAQTm9sBekiweqXVc" + "&returl=" + path;
//        }
        return userInfoUrl;
    }


    public void sendSymptomQuestion(UserEntity userEntity) {

        if (userEntity.getThyroidSymptom() != 1) {
            String msgText = "您好，我是甲状腺咨询智能助理，请回复您当前的疾病症状，如发送：甲状腺疾病、有甲状腺结节、有甲状腺肿瘤、甲功异常、甲状腺炎、甲亢、甲减。";
            MsgRecordEntity msgRecordEntity = iMsgRecordService.getOne(
                    Wrappers.<MsgRecordEntity>lambdaQuery()
                            .eq(MsgRecordEntity::getToUid, userEntity.getUid())
                            .eq(MsgRecordEntity::getFromUid, serviceUid)
                            .ge(MsgRecordEntity::getMsgTime, LocalDate.now())
                            .eq(MsgRecordEntity::getCloudCustomData, "symptom_question")
                            .isNotNull(MsgRecordEntity::getCloudCustomData)

            );
            if (msgRecordEntity == null) {
                Map<String, Object> map = new HashMap<>();
                map.put("Text", msgText);
                adminSendMsg(TimAdminSendMsgData.builder()
                        .syncOtherMachine(1)
                        .fromAccount(serviceUid)
                        .toAccount(userEntity.getUid())
                        .msgLifeTime(604800)
                        .msgRandom((long) RandomUtil.randomInt(100000, 1000000))
                        .msgBody(Collections.singletonList(MsgBody.builder()
                                .msgType(MsgTypeEnum.TIMTextElem.getName())
                                .msgContent(map)
                                .build()))
                        .cloudCustomData("symptom_question")
                        .build());
            }
        }
    }

    public void sendRegisterOrFollowUpMsg(PatientBaseInfoRespDto patientBaseInfoRespDto, UserEntity userEntity) {
        if (userEntity.getThyroidSymptom() == 1) {
            if (patientBaseInfoRespDto == null) {
                MsgRecordEntity msgRecordEntity = iMsgRecordService.getOne(
                        Wrappers.<MsgRecordEntity>lambdaQuery()
                                .eq(MsgRecordEntity::getToUid, userEntity.getUid())
                                .eq(MsgRecordEntity::getFromUid, serviceUid)
                                .ge(MsgRecordEntity::getMsgTime, LocalDate.now())
                                .isNotNull(MsgRecordEntity::getCloudCustomData)
                                .apply("cloud_custom_data ->'$.type' = 13 ")
                );
                if (msgRecordEntity == null) {
                    // 基础信息为空  用户未注册
                    adminSendMsg(TimAdminSendMsgData.builder()
                            .syncOtherMachine(1)
                            .fromAccount(serviceUid)
                            .toAccount(userEntity.getUid())
                            .msgLifeTime(604800)
                            .msgRandom((long) RandomUtil.randomInt(100000, 1000000))
                            .msgBody(Collections.singletonList(MsgBody.builder()
                                    .msgType(MsgTypeEnum.TIMCustomElem.getName())
                                    .msgContent(TIMCustomData.builder()
                                            .Data("请点击下方按钮进行注册")
                                            .build())
                                    .build()))
                            .cloudCustomData(JSONUtil.toJsonStr(CloudCustomData.builder()
                                    .type(13)
                                    .content("点击注册")
                                    .url(getRegisterUrl(userEntity.getOpenId(), userEntity.getUid()))
                                    .build()))
                            .build());
                }
            } else {
                String faceUrl;
                if (patientBaseInfoRespDto.getPatGender().equals("男")) {
                    faceUrl = "https://upload.weiheyixue.com/avatar_man.png";
                } else {
                    faceUrl = "https://upload.weiheyixue.com/avatar_woman.png";
                }
                userEntity.setHeaderUrl(faceUrl);
                userEntity.setName(patientBaseInfoRespDto.getPatName());


                MsgRecordEntity msgRecordEntity = iMsgRecordService.getOne(
                        Wrappers.<MsgRecordEntity>lambdaQuery()
                                .eq(MsgRecordEntity::getToUid, userEntity.getUid())
                                .eq(MsgRecordEntity::getFromUid, serviceUid)
                                .ge(MsgRecordEntity::getMsgTime, LocalDate.now())
                                .isNotNull(MsgRecordEntity::getCloudCustomData)
                                .apply("cloud_custom_data ->'$.type' = 14 ")
                );
                if (msgRecordEntity == null) {
                    // 判断用户是否登记随访
                    String lastPatFill = patientBaseInfoRespDto.getLastPatCheckin();
                    if (StringUtils.isBlank(lastPatFill)) {
//                    if (true) {
                        // 问卷/登记随访
                        CloudCustomData cloudCustomData = CloudCustomData.builder()
                                .type(14)
                                .content("点击登记")
                                .url(getFollowUpUrl(userEntity.getOpenId(), userEntity.getUid()))
                                .status(2)
                                .build();
                        adminSendMsg(TimAdminSendMsgData.builder()
                                .syncOtherMachine(1)
                                .fromAccount(serviceUid)
                                .toAccount(userEntity.getUid())
                                .msgLifeTime(604800)
                                .msgRandom((long) RandomUtil.randomInt(100000, 1000000))
                                .msgBody(Collections.singletonList(MsgBody.builder()
                                        .msgType(MsgTypeEnum.TIMCustomElem.getName())
                                        .msgContent(TIMCustomData.builder()
                                                .Data("请先登记您的就诊信息")
                                                .build())
                                        .build()))
                                .cloudCustomData(JSONUtil.toJsonStr(cloudCustomData))
                                .build());
                    }

                } else {
                    if (userEntity.getGreetingMsg() == 0) {
                        userEntity.setGreetingMsg(1);
                    }
                }
                String lastPatFill = patientBaseInfoRespDto.getLastPatCheckin();
                if (StringUtils.isNotBlank(lastPatFill)) {
                    MsgRecordEntity robotMsg = iMsgRecordService.getOne(
                            Wrappers.<MsgRecordEntity>lambdaQuery()
                                    .eq(MsgRecordEntity::getToUid, userEntity.getUid())
                                    .eq(MsgRecordEntity::getFromUid, serviceUid)
                                    .ge(MsgRecordEntity::getMsgTime, LocalDate.now())
                                    .isNotNull(MsgRecordEntity::getCloudCustomData)
                                    .eq(MsgRecordEntity::getCloudCustomData,"已完成登记。")
                    );
                    if (robotMsg == null) {
                        adminSendMsg(TimAdminSendMsgData.builder()
                                .syncOtherMachine(1)
                                .fromAccount(serviceUid)
                                .toAccount(userEntity.getUid())
                                .msgLifeTime(604800)
                                .msgRandom((long) RandomUtil.randomInt(100000, 1000000))
                                .msgBody(Collections.singletonList(MsgBody.builder()
                                        .msgType(MsgTypeEnum.TIMTextElem.getName())
                                        .msgContent(TIMCustomData.builder()
                                                .Data("已完成登记。")
                                                .build())
                                        .build()))
                                .cloudCustomData("已完成登记。")
                                .build());
                    }
                }
                iUserService.saveOrUpdate(userEntity);
            }
        }
    }

}